<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="logo">NEWBE工作室</div>
      <div class="nav-container">
        <router-link to="/sales/orders" class="nav-item" :class="{ 'active': route.path.startsWith('/sales') }">
          <i class="el-icon-shopping-cart"></i>
          <span>销售订单</span>
        </router-link>
        <router-link to="/attendance" class="nav-item" :class="{ 'active': route.path.startsWith('/attendance') }">
          <i class="el-icon-time"></i>
          <span>考勤与薪资</span>
        </router-link>
        <router-link to="/management" class="nav-item" :class="{ 'active': route.path.startsWith('/management') }" v-if="userStore.isAdmin()">
          <i class="el-icon-setting"></i>
          <span>销售管理</span>
        </router-link>
      </div>
      <div class="user-info">
        <el-dropdown @command="handleCommand" trigger="click" class="user-dropdown">
          <span class="user-dropdown-link">
            {{ userInfo.nickname || userInfo.username }}
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人资料</el-dropdown-item>
              <el-dropdown-item command="password">修改密码</el-dropdown-item>
              <el-dropdown-item divided command="logout">注销</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 次级导航栏 -->
    <el-header v-if="showSubMenu" class="sub-header">
      <div class="sub-nav-container">
        <!-- 销售订单子菜单 -->
        <template v-if="activeMenu === '/sales/orders'">
          <router-link to="/sales/orders" class="sub-nav-item" :class="{ 'active': isActive('/sales/orders') }">订单明细记录</router-link>
          <router-link to="/sales/customers" class="sub-nav-item" :class="{ 'active': isActive('/sales/customers') }">客户信息维护</router-link>
          <router-link to="/sales/products" class="sub-nav-item" :class="{ 'active': isActive('/sales/products') }">产品信息维护</router-link>
          <router-link to="/sales/expirations" class="sub-nav-item" :class="{ 'active': isActive('/sales/expirations') }">产品授权到期表</router-link>
          <router-link to="/sales/server-rental" class="sub-nav-item" :class="{ 'active': isActive('/sales/server-rental') }">主机出租</router-link>
          <router-link to="/sales/commission-categories" class="sub-nav-item" :class="{ 'active': isActive('/sales/commission-categories') }" v-if="userStore.isAdmin()">提成分类管理</router-link>
        </template>
        
        <!-- 考勤与薪资子菜单 -->
        <template v-if="activeMenu === '/attendance'">
          <router-link to="/attendance/record" class="sub-nav-item" :class="{ 'active': isActive('/attendance/record') }">工时填报</router-link>
          <router-link to="/attendance/calendar" class="sub-nav-item" :class="{ 'active': isActive('/attendance/calendar') }">值班日历</router-link>
          <router-link to="/attendance/salary" class="sub-nav-item" :class="{ 'active': isActive('/attendance/salary') }">薪资汇总</router-link>
          <router-link to="/attendance/detail" class="sub-nav-item" :class="{ 'active': isActive('/attendance/detail') }">工时薪资明细</router-link>
          <router-link to="/attendance/commission" class="sub-nav-item" :class="{ 'active': isActive('/attendance/commission') }">激活提成明细</router-link>
        </template>
        
        <!-- 销售管理子菜单 -->
        <template v-if="activeMenu === '/management'">
          <router-link to="/management/employees" class="sub-nav-item" :class="{ 'active': isActive('/management/employees') }">员工管理</router-link>
          <router-link to="/management/dashboard" class="sub-nav-item" :class="{ 'active': isActive('/management/dashboard') }">销售情况</router-link>
        </template>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main>
      <router-view />
    </el-main>

    <!-- 对话框组件 -->
    <el-dialog v-model="dialogVisible.profile" title="个人资料" width="500px">
      <el-form :model="profileForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="profileForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="profileForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="profileForm.phone_number"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.profile = false">取消</el-button>
          <el-button type="primary" @click="updateProfile">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible.password" title="修改密码" width="500px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.password = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AppLayout'
}
</script>

<script setup>
import { computed, reactive, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';
import { ArrowDown } from '@element-plus/icons-vue';
import { updateUserProfile, changePassword } from '@/api/user';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const passwordFormRef = ref(null);

// 获取用户信息
const userInfo = computed(() => userStore.userInfo);

// 对话框可见性控制
const dialogVisible = reactive({
  profile: false,
  password: false
});

// 个人资料表单
const profileForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phone_number: ''
});

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 密码表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ]
};

// 计算当前活动的主菜单项
const activeMenu = computed(() => {
  const path = route.path;
  if (path.startsWith('/sales')) {
    return '/sales/orders';
  } else if (path.startsWith('/attendance')) {
    return '/attendance';
  } else if (path.startsWith('/management')) {
    return '/management';
  }
  return path;
});

// 是否显示子菜单
const showSubMenu = computed(() => {
  return route.path.startsWith('/sales') || 
         route.path.startsWith('/attendance') || 
         route.path.startsWith('/management');
});

// 判断是否为活动子导航项
const isActive = (path) => {
  return route.path === path;
};

// 打开个人资料对话框
const openProfileDialog = () => {
  // 填充表单数据
  Object.assign(profileForm, userInfo.value);
  dialogVisible.profile = true;
};

// 更新个人资料
const updateProfile = async () => {
  try {
    const response = await updateUserProfile(profileForm);
    if (response.code === 200) {
      ElMessage.success(response.message || '个人资料更新成功');
      // 更新本地存储的用户信息
      userStore.setUserInfo({
        ...userInfo.value,
        ...profileForm
      });
      dialogVisible.profile = false;
    } else {
      ElMessage.error(response.message || '更新失败');
    }
  } catch (error) {
    console.error('更新个人资料失败:', error);
    ElMessage.error('更新失败，请稍后重试');
  }
};

// 更新密码
const updatePassword = async () => {
  if (!passwordFormRef.value) return;
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await changePassword({
          old_password: passwordForm.oldPassword,
          new_password: passwordForm.newPassword
        });
        
        if (response.code === 200) {
          // 成功消息显示为绿色
          ElMessage.success('密码修改成功，即将退出系统');
          
          // 密码修改成功后，重置表单并关闭对话框
          passwordForm.oldPassword = '';
          passwordForm.newPassword = '';
          passwordForm.confirmPassword = '';
          dialogVisible.password = false;
          
          // 2秒后强制登出
          setTimeout(async () => {
            await userStore.userLogout();
            router.push('/login');
          }, 2000);
        } else {
          // 显示错误信息
          ElMessage.error(response.message || '密码修改失败');
        }
      } catch (error) {
        console.error('密码修改失败:', error);
        ElMessage.error('密码修改失败，请稍后重试');
      }
    }
  });
};

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'profile') {
    openProfileDialog();
  } else if (command === 'password') {
    dialogVisible.password = true;
  } else if (command === 'logout') {
    ElMessageBox.confirm('确定要注销登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await userStore.userLogout();
      router.push('/login');
    }).catch(() => {});
  }
};
</script>

<style scoped>
.app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.header {
  display: flex;
  align-items: center;
  padding: 0 20px;
  background-color: #409EFF;
  color: white;
  height: 60px;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  margin-right: 20px;
}

.nav-container {
  display: flex;
  height: 100%;
}

.nav-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  color: white;
  text-decoration: none;
  font-size: 16px;
  height: 100%;
  cursor: pointer;
}

.nav-item:hover {
  background-color: #66b1ff;
}

.nav-item.active {
  background-color: #66b1ff;
  font-weight: 500;
}

.sub-header {
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  background-color: #f5f7fa;
  height: 50px;
}

.sub-nav-container {
  display: flex;
  height: 100%;
}

.sub-nav-item {
  display: flex;
  align-items: center;
  padding: 0 15px;
  color: #303133;
  text-decoration: none;
  font-size: 14px;
  height: 100%;
  cursor: pointer;
}

.sub-nav-item:hover {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.sub-nav-item.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
  font-weight: 500;
}

.user-info {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.user-dropdown {
  cursor: pointer;
}

.user-dropdown-link {
  display: flex;
  align-items: center;
  color: white;
}

.el-main {
  background-color: #f0f2f5;
  padding: 0 20px 20px 20px;
  flex: 1;
  overflow-y: auto;
}
</style> 